package com.guanghua.brick.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 对List<Map<String, String>>类型的result进行轮训和修改的助手类
 * @author leeon
 *
 */
public class QueryResultHelper {
	private List<Map<String, String>> result = null;
	private List<QueryResultRowListener> listeners = new ArrayList<QueryResultRowListener>();
	private int index = -1;
	
	private QueryResultHelper() {}
	
	public QueryResultHelper(List<Map<String, String>> result) {
		this.result = result;
		this.index = -1;
	}
	
	public List<String> getColumn(String column) {
		List<String> list = new ArrayList<String>();
		for (Map<String, String> row : result) {
			list.add(row.get(column));
		}
		return list;
	}
	
	public String getColumnByCommaString(String column) {
		StringBuffer ret = new StringBuffer();
		for (Map<String, String> row : result) {
			ret.append(",").append((row.get(column)));
		}
		return (ret.length() != 0)?ret.substring(1).toString():"";
	}
	
	public String getString(String column) {
		return getRow().get(column);
	}
	
	public void setString(String column, String value) {
		getRow().put(column, value);
	}
	
	public Map<String, String> getRow() {
		return result.get(index);
	}
	
	public void setRow(Map<String, String> row) {
		result.set(index, row);
	}
	
	public void addRow() {
		result.add(new HashMap<String, String>());
		index = result.size() - 1;
	}
	
	public boolean next() {
		return ++index < result.size();
	}
	
	public boolean previous() {
		return --index >= 0;
	}
	
	public boolean first() {
		index = 0;
		return index < result.size();
	}
	
	public boolean last() {
		index = result.size() - 1;
		return index >= 0;
	}
	
	public boolean isFirst() {
		return index == 0 && index < result.size();
	}
	
	public boolean isLast() {
		return index == result.size() - 1 && index >= 0;
	}
	
	public void beforeFirst() {
		index = -1;
	}
	
	public void afterLast() {
		index = result.size();
	}
	
	public boolean isBeforeFirst() {
		return index == -1;
	}
	
	public boolean isAfterLast() {
		return index == result.size();
	}
	
	public List<Map<String, String>> toList() {
		return this.result;
	}
	
	/**
	 * 设置结果集的别名，比如alias为"userName, userId, USER_ADDRESS=userAddress"
	 * @param alias
	 */
	public void setAlias(String alias) {
		if (alias == null || alias.length() == 0) return;
		
		//处理别名字符串为map结构
		String[] as = alias.split(",");
		HashMap<String, String> am = new HashMap<String, String>();
		for (int i = 0; i < as.length; i++) {
			as[i] = as[i].trim();
			int j = as[i].indexOf('=');
			if (j == -1)
				am.put(as[i].toUpperCase(), as[i]);
			else
				am.put(as[i].substring(0, j).toUpperCase(), as[i].substring(j+1));
		}
		
		//遍历并且修改别名
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Iterator<Map<String, String>> i = result.iterator();
		while (i.hasNext()) {
			//新行
			Map<String, String> newRow = new HashMap<String, String>();
			//老行
			Map<String, String> row = i.next();
			Iterator<String> j = row.keySet().iterator();
			while (j.hasNext()) {
				String key = j.next();
				//如果存在key,将现在的key按照am中对应的值放入新行
				if (am.containsKey(key)) {
					newRow.put(am.get(key), row.get(key));
				} else {
					newRow.put(key, row.get(key));
				}
			}
			//新行添加到新列表
			list.add(newRow);
		}
		//替换列表
		this.result.clear();
		this.result.addAll(list);
	}
	
	/**
	 * toString的方法，用于打印
	 */
	public String toString() {
		StringBuffer to = new StringBuffer();
		Iterator<Map<String, String>> i = result.iterator();
		while (i.hasNext()) {
			Map<String, String> row = i.next();
			Iterator<String> j = row.keySet().iterator();
			while (j.hasNext()) {
				String key = j.next();
				to.append(key)
				.append(":\t\t\t")
				.append(row.get(key))
				.append("\n");
			}
			to.append("-----------------------------------------------------------------\n");
		}
		return to.toString();
	}

	public List<QueryResultRowListener> getListeners() {
		return listeners;
	}

	public void addListener(QueryResultRowListener listener) {
		this.listeners.add(listener);
	}
	
	public void clearListeners() {
		this.listeners.clear();
	}
	
	/**
	 * 轮循rows，根据listner处理的结果，updaterow，并且输出到一个新的list，map中
	 * @return
	 */
	public List<Map<String, Object>> calculateQueryResult() {
		List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
		
		this.beforeFirst();
		while (this.next()) {
			Map<String, String> row = this.getRow();
			Map<String, Object> newRow = new HashMap<String, Object>();
			newRow.putAll(row);
			for (int i = 0; i < this.listeners.size(); i ++) {
				String key = this.listeners.get(i).modifyKey();
				Object value = this.listeners.get(i).modifyValue(row);
				newRow.put(key, value);
			}
			ret.add(newRow);
		}
		return ret;
	}
	
	
	public List<Object> toObject(Class objClass) {
		return null;
	}
}
